package com.probox.common.entity.service.product.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.Arrays;
import java.util.List;

import com.probox.common.core.constant.CachePrefix;
import com.probox.common.core.enums.DataStatus;
import com.probox.common.core.exception.BaseException;
import com.probox.common.core.exception.ProductException;
import com.probox.common.core.utils.SecurityUtils;
import com.probox.common.core.utils.StringUtils;
import com.probox.common.redis.service.RedisService;
import com.probox.common.entity.domain.product.ProductInfoTags;
import com.probox.common.entity.service.product.IProductTagsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.probox.common.entity.mapper.product.ProductTagsMapper;
import com.probox.common.entity.domain.product.ProductTags;
import org.springframework.transaction.annotation.Transactional;

/**
 * 商品标签信息Service业务层处理
 *
 * @date 2021-05-27
 */
@Service
@Transactional
public class ProductTagsServiceImpl extends ServiceImpl<ProductTagsMapper, ProductTags> implements IProductTagsService {
    @Autowired
    private ProductTagsMapper productTagsMapper;

    @Autowired
    private ProductInfoTagsServiceImpl productInfoTagsService;

    @Autowired
    private RedisService redisService;

    /**
     * 查询商品标签信息
     *
     * @param tagsUid 商品标签信息ID
     * @return 商品标签信息
     */
    @Override
    public ProductTags selectProductTagsById(Long tagsUid) {
        return this.getById(tagsUid);
    }

    /**
     * 查询商品标签信息列表
     *
     * @param productTags 商品标签信息
     * @return 商品标签信息
     */
    @Override
    public List<ProductTags> queryList(ProductTags productTags) {
        QueryWrapper<ProductTags> queryWrapper = Wrappers.query();
        if (StringUtils.isNotEmpty(String.valueOf(productTags.getTagsName())) && productTags.getTagsName() != null) {
            queryWrapper.like("TAGS_NAME", productTags.getTagsName());
        }
        if (StringUtils.isNotEmpty(String.valueOf(productTags.getDataStatus())) && productTags.getDataStatus() != null) {
            queryWrapper.eq("DATA_STATUS", productTags.getDataStatus());
        }
        Long platformId = SecurityUtils.getPlatformId();
        if (platformId == null) {
            throw new BaseException("当前账号异常");
        }
        queryWrapper.eq("PLATFORM_UID", platformId);
        queryWrapper.ne("DATA_STATUS", DataStatus.delete.getKey());
        if (StringUtils.isNotEmpty(String.valueOf(productTags.getDataPriority())) && productTags.getDataPriority() != null) {
            queryWrapper.orderByAsc("DATA_PRIORITY");
        } else {
            queryWrapper.orderByAsc("DATA_PRIORITY");
            queryWrapper.orderByDesc("UPDATE_TIME");
        }
        return productTagsMapper.selectList(queryWrapper);
    }

    /**
     * 新增商品标签信息
     *
     * @param productTags 商品标签信息
     * @return 结果
     */
    @Override
    public boolean insertProductTags(ProductTags productTags) {
        // 名称不能重名
        Integer result = queryName(productTags.getTagsName(), null);
        if (result > 0) {
            throw new ProductException("商品标签名称不能重名！");
        }
        Long userId = SecurityUtils.getUserId();
        DateTime date = DateUtil.date();
        String username = SecurityUtils.getUsername();
        productTags.setPlatformUid(SecurityUtils.getPlatformId());
        productTags.setUpdateUid(userId);
        productTags.setUpdateName(username);
        productTags.setUpdateTime(date);
        productTags.setDataStatus(DataStatus.valid.getKey());
        productTags.setCreateTime(date);
        productTags.setCreateName(username);
        productTags.setCreateUid(userId);
        redisService.deleteObject(CachePrefix.PRODUCT_TAGS_SELECT + SecurityUtils.getPlatformId());
        return this.save(productTags);

    }

    /**
     * 修改商品标签信息
     *
     * @param productTags 商品标签信息
     * @return 结果
     */
    @Override
    public boolean updateProductTags(ProductTags productTags) {
        // 名称不能重名
        Integer result = queryName(productTags.getTagsName(), productTags.getTagsUid());
        if (result > 0) {
            throw new ProductException("商品标签名称不能重名！");
        }
        productTags.setUpdateUid(SecurityUtils.getUserId());
        productTags.setUpdateName(SecurityUtils.getUsername());
        productTags.setUpdateTime(DateUtil.date());
        redisService.deleteObject(CachePrefix.PRODUCT_TAGS_SELECT + SecurityUtils.getPlatformId());

        return this.updateById(productTags);
    }

    /**
     * 批量删除商品标签信息
     *
     * @param tagsUids 需要删除的商品标签信息ID
     * @return 结果
     */
    @Override
    public boolean deleteProductTagsByIds(Long[] tagsUids) {
        UpdateWrapper<ProductTags> updateWrapper = new UpdateWrapper<>();
        updateWrapper.in("TAGS_UID", Arrays.asList(tagsUids));
        updateWrapper.set("DATA_STATUS", DataStatus.delete.getKey());
        updateWrapper.set("UPDATE_UID", SecurityUtils.getUserId());
        updateWrapper.set("UPDATE_NAME", SecurityUtils.getUsername());
        updateWrapper.set("UPDATE_TIME", DateUtil.date());
        return this.update(updateWrapper);
    }

    /**
     * 防止重名
     *
     * @param name 名字
     * @param uid  类别ID
     * @return
     */
    public Integer queryName(String name, Long uid) {
        QueryWrapper<ProductTags> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("TAGS_NAME", name);
        queryWrapper.ne("DATA_STATUS", DataStatus.delete.getKey());
        queryWrapper.eq("PLATFORM_UID", SecurityUtils.getPlatformId());
        if (ObjectUtil.isNotEmpty(uid)) {
            queryWrapper.ne("TAGS_UID", uid);
        }
        Integer integer = productTagsMapper.selectCount(queryWrapper);
        return integer;
    }

    /**
     * 获取商品标签的name
     *
     * @param productUid
     * @return
     */
    @Override
    public String getTagsName(Long productUid) {
        StringBuffer tagsName = new StringBuffer();
        List<ProductInfoTags> productInfoTags = productInfoTagsService.queryList(productUid);
        if (ObjectUtil.isNotEmpty(productInfoTags)) {
            Long[] uids = new Long[productInfoTags.size()];
            int index = 0;
            for (ProductInfoTags tags : productInfoTags) {
                uids[index] = tags.getTagsUid();
                index++;
            }
            QueryWrapper<ProductTags> queryWrapper = Wrappers.query();
            queryWrapper.in("TAGS_UID", uids);
            List<ProductTags> productTags = productTagsMapper.selectList(queryWrapper);
            if (ObjectUtil.isNotEmpty(productTags)) {
                productTags.forEach(tags -> tagsName.append("," + tags.getTagsName()));
                String s = tagsName.toString();
                return s.substring(1, s.length());
            }

        }
        return tagsName.toString();
    }

    /**
     * 获取商品标签的下拉框
     *
     * @return
     */
    @Override
    public List<ProductTags> bulidSelect() {
        Long platformId = SecurityUtils.getPlatformId();
        if (platformId == null) throw new BaseException("当前账号异常");
        String key = CachePrefix.PRODUCT_TAGS_SELECT + platformId;
        List<ProductTags> list = redisService.getCacheList(key);
        if (ObjectUtil.isEmpty(list)) {
            QueryWrapper<ProductTags> queryWrapper = Wrappers.query();
            queryWrapper.eq("PLATFORM_UID", platformId);
            queryWrapper.eq("DATA_STATUS", DataStatus.valid.getKey());
            queryWrapper.orderByAsc("DATA_PRIORITY");
            list = productTagsMapper.selectList(queryWrapper);
            if (ObjectUtil.isNotEmpty(list)) redisService.setCacheList(key, list);
        }
        return list;
    }

    @Override
    public String getTagsNameByProductId(Long productId) {
        QueryWrapper<ProductTags> queryWrapper = Wrappers.query();
        queryWrapper.eq("DATA_STATUS", DataStatus.valid.getKey());
        queryWrapper.last(" and TAGS_UID in (SELECT TAGS_UID from product_info_tags where PRODUCT_UID="+productId+" and DATA_STATUS='1' ) ");
        List<ProductTags> list = productTagsMapper.selectList(queryWrapper);
        StringBuffer rst = new StringBuffer();
        for(ProductTags tags:list){
            if (rst.length()>0)
                rst.append(",");
            rst.append(tags.getTagsName());
        }
        return rst.toString();
    }


    public void delLike(){

    }
}
